import type { App } from 'vue';
// 引入 nprogress 相关方法
import { close, start } from '@/utils/nprogress';
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
// 引入 login.ts
import LoginRouter from './modules/login';
// 引入 test.ts
import TestRouter from './modules/test';

export const publicRoutes: Array<RouteRecordRaw> = [
	{
			path: '/login',
			name: 'login',
			
			component: () => import('@/views/user/login-page.vue'),
			meta: {
				title: '登录'
			},
		},
	{
		path: '/',
		name: '/',
		component: () => import('@/layout/index.vue'),
		children: [
			...TestRouter
		]
  },
	// ...LoginRouter,
	// ...TestRouter
];

// 定义router
const router = createRouter({
	history: createWebHashHistory(),
	routes: publicRoutes
});

// 路由前置后卫
router.beforeEach((to, from, next) => {
	// 开启进度条
	start();
	const token = window.localStorage.getItem('token')
	//校验非登录页面的登陆状态
	if (to.path !== '/login') {
			//判断用户是否登录
			if (token) {
					next()
			} else {
					alert('您还未登录，请先登录帐号')
					next('/login')
			}
	} else {
			next()
	}

});
// 路由后置后卫
router.afterEach(() => {
	// 关闭进度条
	close();
});

/* 初始化路由表 */
export function resetRouter() {
	router.getRoutes().forEach((route) => {
		const { name } = route;
		if (name) {
			router.hasRoute(name) && router.removeRoute(name);
		}
	});
}
export default router;
export const setupRouter = (app: App<Element>) => {
	app.use(router);
};

